<template>
  <el-dialog title="分配角色" :visible="showRoleDialog" @close="btnCancel">
    <el-checkbox-group v-model="roleIds">
      <el-checkbox v-for="item in list" :key="item.id" :label="item.id">
        {{ item.name }}
      </el-checkbox>
    </el-checkbox-group>

    <el-row slot="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button type="primary" size="small" @click="btnOk">确定</el-button>
        <el-button size="small" @click="btnCancel">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { assignRoles } from '@/api/employees'
import { getRoleList } from '@/api/setting'
import { getUserDetailById } from '@/api/user'
export default {
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    // 用户的id 用来查询当前用户的角色信息
    userId: {
      type: String,
      default: null,
      required: true
    }
  },

  data () {
    return {
      roleIds: [], // 负责存储当前用户拥有的角色id
      list: [] // 所有角色ID
    }
  },
  created () {
    this.getRoleList()
  },

  methods: {
    async btnOk () {
      await assignRoles({ id: this.userId, roleIds: this.roleIds })
      this.$emit('update:showRoleDialog', false)
      this.$message.success('操作成功')
    },

    btnCancel () {
      this.roleIds = [] // 清空原来的数组
      this.$emit('update:showRoleDialog', false)
    },

    // 获取角色详情
    async getUserDetailById (id) {
      const { roleIds } = await getUserDetailById(id) // props传值是异步的，不能用this.userId
      this.roleIds = roleIds
    },

    // 获取角色列表
    async getRoleList () {
      const { rows } = await getRoleList({ page: 1, pagesize: 20 })
      this.list = rows
    }
  }
}
</script>

<style>
</style>
